package com.gzy.cs3.contoller;

import com.gzy.cs3.model.User;
import com.gzy.cs3.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询所有用户
    @GetMapping
    @ApiOperation(value = "查询所有用户", notes = "返回所有用户列表")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    // 通过ID查询用户
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询用户", notes = "根据用户ID查询用户信息")
    @ApiParam(name = "id", value = "用户ID", required = true)
    public ResponseEntity<User> getUserById(@PathVariable int id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.ok(user);
    }

    // 插入用户
    @PostMapping
    @ApiOperation(value = "插入用户", notes = "插入一个新的用户")
    public ResponseEntity<Void> createUser(@RequestBody User user) {
        try {
            userService.insertUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // 更新用户。
    @PutMapping("/{id}")
    @ApiOperation(value = "更新用户", notes = "更新指定ID的用户信息")
    @ApiParam(name = "id", value = "用户ID", required = true)
    public ResponseEntity<Void> updateUser(@PathVariable int id, @RequestBody @ApiParam(name = "user", value = "用户对象", required = true) User user) {
        user.setId(id);
        userService.updateUser(user);
        return ResponseEntity.ok().build();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户", notes = "删除指定ID的用户")
    @ApiParam(name = "id", value = "用户ID", required = true)
    public ResponseEntity<Void> deleteUser(@PathVariable int id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}
